﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GMAC.ReportingSystem.Business.Components;
using GMAC.ReportingSystem.Business.Entities.Configuration;
using GMAC.ReportingSystem.Business.Entities;
using System.Data;
using System.Drawing;
using System.Text;
using FrameworkManapro.Utilities;
using System.IO;
using System.Collections;
using System.IO.Compression;
using System.Configuration;
using GMAC.DirectDebit.Common;


namespace GMAC.ReportingSystem.Paginas
{
    public partial class UploadALSTELECOM : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated || Session["User"] == null)
            {
                System.Web.Security.FormsAuthentication.RedirectToLoginPage();
                return;
            } // if

            if (IsPostBack) return;
            Initializate();
        } // Page_Load

        #region Buttons Events
           
            protected void btnLoadFile_Click(object sender, ImageClickEventArgs e)
            {
                    popupExtenderLoadFile.Show();
            } // btnLoadFile_Click

            protected void btnExportToExcel_Click(object sender, ImageClickEventArgs e)
            {
                try
                {
                    StringBuilder str = new StringBuilder();
                    var fileFunctions = new FileFunctions();
                    StringASLTelecomCollection col = (StringASLTelecomCollection)Session["ASLInvalidsCollection"];

                    fileFunctions.fileName = fileFunctions.BuildFileName("ASLTelecom", "_XLS") + ".xls";
                    str = fileFunctions.BuildDataTable_ASLTelecom(col, "\t");
                    fileFunctions.GenerateFilexls(str, this.Response);

                } // try
                catch (Exception ex)
                {
                    FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Export", "btnExportToExcel_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                    wucMessage.ShowMessage(UserControls.MessageType.Error, "An error occurred exporting file.", ex.ToString());
                    popupExtenderMessage.Show();
                } // catch


                #region "Codigo anterior"
                    //try
                    //{
                    //    var sw = new System.IO.StringWriter();
                    //    var htw = new HtmlTextWriter(sw);
                    //    grvFailed.RenderControl(htw);
                    //    Response.Clear();
                    //    Response.AddHeader("content-disposition",
                    //                       string.Format("attachment; filename=FailedPayments_{0}.xls",
                    //                                     DateTime.Today.ToShortDateString()));
                    //    Response.Charset = "";
                    //    Response.ContentType = "application/vnd.xls";
                    //    Response.Write(sw.ToString());
                    //    Response.End();

                    //} // try
                    //catch (Exception ex)
                    //{
                    //    FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Export to Excel", ex.TargetSite.Name.ToString(), System.Diagnostics.TraceEventType.Error, ex.StackTrace.ToString());
                    //    wucMessage.ShowMessage(UserControls.MessageType.Error, "an error occurred exporting to excel." + " " + ex.Message.ToString(), null);
                    //    popupExtenderMessage.Show();
                    //} // catch
                #endregion

            } // btnExportToExcel_Click

            protected void btnSuccessful_Click(object sender, EventArgs e)
            {
                grvSuccessful.Visible = true;
                grvFailed.Visible = false;
                btnSuccessful.Enabled = false;
                btnFailed.Enabled = true;
                spanGridTitleFailed.Visible = false;
                spanGridTitleSuccessful.Visible = true;
                btnExportToExcel.Visible = false;
                btnProcessFile.Visible = true;
            } // btnSuccessful_Click

            protected void btnFailed_Click(object sender, EventArgs e)
            {
                grvFailed.Visible = true;
                grvSuccessful.Visible = false;
                btnSuccessful.Enabled = true;
                btnFailed.Enabled = false;
                spanGridTitleSuccessful.Visible = false;
                spanGridTitleFailed.Visible = true;
                btnExportToExcel.Visible = true;
                btnProcessFile.Visible = false;
            } // btnFailed_Click

            protected void btnSendFile_Click(object sender, ImageClickEventArgs e)
            {
                if (wucFileUploadLoans.FileName.Trim() == string.Empty)
                {
                    wucMessage.ShowMessage(UserControls.MessageType.Information, "Select a file.", null);
                    popupExtenderMessage.Show();
                } // if
                else
                {
                    try
                    {
                        
                            var fileName = wucFileUploadLoans.FileName;
                            var dotpos = fileName.LastIndexOf(".");
                            var extension = fileName.Substring(dotpos + 1, fileName.Length - dotpos - 1);
                            fileName = fileName.Substring(0, dotpos);
                            var path = MapPath("~") + @"\DebitAccount\";
                            if (!System.IO.Directory.Exists(path))
                                System.IO.Directory.CreateDirectory(path);

                            fileName += "-" + Guid.NewGuid() + "." + extension;
                            ViewState["fileName"] = @"\DebitAccount\" + fileName;
                            fileName = path + fileName;

                            if (boolValidLengthFile(fileName) == false)
                            {
                                wucMessage.ShowMessage(UserControls.MessageType.Information, "Make sure the file name or path does not have more than 218 characters.", null);
                                popupExtenderMessage.Show();
                                return;
                            } // if (boolValidLengthFile(fileName) == false)
                            

                            wucFileUploadLoans.SaveFile(fileName);
                            txtFileUploaded.Text = wucFileUploadLoans.FileName;
                            var processDate = DateTime.Now;

                            // Declara las colecciones que se usaran para capturar los validos e invalidos
                            StringASLTelecomCollection ASLInvalids = new StringASLTelecomCollection();
                            StringASLTelecomCollection ASLValids = new StringASLTelecomCollection();

                            // Declara la clase que referencia el componente de negocios
                            ASLTelecomComponent bc = new ASLTelecomComponent();

                            bc.LoadFile(processDate, fileName, ((User)Session["User"]).UserID, ref ASLInvalids, ref ASLValids);

                            //grvSuccessful.DataSource = ASLValids;
                            //grvSuccessful.DataBind();
                            //grvFailed.DataSource = ASLInvalids;
                            //grvFailed.DataBind();

                            Session["ASLValidsCollection"] = ASLValids;
                            grvSuccessful.AllowPaging = true;
                            grvSuccessful.PageIndex = 0;
                            grvSuccessful.AllowSorting = true;
                            grvSuccessful.PageSize = int.Parse(System.Configuration.ConfigurationManager.AppSettings["PageCount"]);
                            grvSuccessful.DataSource = ASLValids;
                            grvSuccessful.DataBind();

                            Session["ASLInvalidsCollection"] = ASLInvalids;
                            grvFailed.AllowPaging = true;
                            grvFailed.PageIndex = 0;
                            grvFailed.AllowSorting = true;
                            grvFailed.PageSize = int.Parse(System.Configuration.ConfigurationManager.AppSettings["PageCount"]);
                            grvFailed.DataSource = ASLInvalids;
                            grvFailed.DataBind();



                            //ViewState["SuccessCount"] = valids.Count;
                            //ViewState["FailedCount"] = invalids.Count;
                            lblResults.Text = String.Format("{0} Records successfully loaded. {1} Records failed", ViewState["SuccessCount"], ViewState["FailedCount"]);
                            btnSuccessful.Visible = true;
                            btnFailed.Visible = true;
                            if (e != null) btnSuccessful_Click(sender, e);
                        
                    } // try
                    catch (Exception ex)
                    {
                        if (ex.Message.Contains("File invalid"))
                        {
                            wucMessage.ShowMessage(UserControls.MessageType.Error, ex.Message, ex.ToString());
                            popupExtenderMessage.Show();
                        } // if
                        else
                        {
                            FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Send File", "btnSendFile_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                            wucMessage.ShowMessage(UserControls.MessageType.Error, "An error occurred sending file.", ex.ToString());
                            popupExtenderMessage.Show();
                        } // else

                    } // catch
                } // else

            } // btnSendFile_Click

            protected void btnAceptar_Click(object sender, ImageClickEventArgs e)
            {

            } // btnAceptar_Click

            protected void btnProcessFile_Click(object sender, ImageClickEventArgs e)
            {
                try
                {
                    ASLTelecomComponent bc = new ASLTelecomComponent();

                    bc.GenerateUploadFile(((User)Session["User"]).UserID);
                    wucMessage.ShowMessage(UserControls.MessageType.Success, "The records ASL Telecom successfully saved.", null);
                    popupExtenderMessage.Show();
                    
                } // try
                catch (Exception ex)
                {
                    FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Generate files",
                                                                                                                           "void Search",
                                                                                                                           System.Diagnostics.TraceEventType.
                                                                                                                               Error, ex.StackTrace);
                    wucMessage.ShowMessage(UserControls.MessageType.Error, "An error has ocurred during the generate files",
                                           ex.ToString());
                    popupExtenderMessage.Show();
                } // catch
            } // btnProcessFile_Click

            public override void VerifyRenderingInServerForm(Control control)
            {

            } // VerifyRenderingInServerForm
            
        #endregion

        #region MyRegion
            private void Initializate()
            {
                this.hidOrderDirFailed.Value = "1";
                this.hidOrderByFailed.Value = "";
                this.hidOrderDirSuccessful.Value = "1";
                this.hidOrderBySuccessful.Value = "";
                btnSuccessful.Visible = false;
                btnFailed.Visible = false;
                spanGridTitleFailed.Visible = false;
                spanGridTitleSuccessful.Visible = false;
                btnExportToExcel.Visible = false;
                btnProcessFile.Visible = false;
            } // Initializate

        #endregion

        #region "Metodos"

            /// <summary>
            /// valida que el archivo (con su ruta) no sea mayor a 218 caracteres
            /// </summary>
            /// <param name="fileName">Nombre del archivo (con su ruta)</param>
            /// <returns>
            /// True : Archivo Valido
            /// False: Archivo Invalido
            /// </returns>
            private bool boolValidLengthFile(string fileName)
            {
                return fileName.Length <= 218;
            } // boolValidLengthFile

            /// <summary>
            /// Cargar los datos.
            /// </summary>
            /// <param name="pagina">The pagina.</param>
            /// <param name="sortExpression">The sort expression.</param>
            /// <param name="direccion">The direccion.</param>
            /// <returns></returns>
            private void CargarDatosInvalids(int pagina, string sortExpression, int direccion)
            {
                // Declara la clase que referencia el componente de negocios
                ASLTelecomComponent bc = new ASLTelecomComponent();

                StringASLTelecomCollection col = new StringASLTelecomCollection();
                col = (StringASLTelecomCollection)Session["ASLInvalidsCollection"];

                string strDireccion = (direccion == 0) ? "ASC" : "DESC";

                col = bc.sord(col, sortExpression, strDireccion);
                Session["ASLInvalidsCollection"] = col;

                this.grvFailed.DataSource = col;
                this.grvFailed.DataBind();
            } // CargarDatosInvalids

            /// <summary>
            /// Cargar los datos.
            /// </summary>
            /// <param name="pagina">The pagina.</param>
            /// <param name="sortExpression">The sort expression.</param>
            /// <param name="direccion">The direccion.</param>
            /// <returns></returns>
            private void CargarDatosValids(int pagina, string sortExpression, int direccion)
            {
                // Declara la clase que referencia el componente de negocios
                ASLTelecomComponent bc = new ASLTelecomComponent();

                StringASLTelecomCollection col = new StringASLTelecomCollection();
                col = (StringASLTelecomCollection)Session["ASLValidsCollection"];

                string strDireccion = (direccion == 0) ? "ASC" : "DESC";

                col = bc.sord(col, sortExpression, strDireccion);
                Session["ASLValidsCollection"] = col;

                this.grvSuccessful.DataSource = col;
                this.grvSuccessful.DataBind();
            } // CargarDatosValids

            protected void grvSuccessful_PageIndexChanging(object sender, GridViewPageEventArgs e)
            {
                grvSuccessful.PageIndex = e.NewPageIndex;
                StringASLTelecomCollection col = new StringASLTelecomCollection();
                col = (StringASLTelecomCollection)Session["ASLValidsCollection"];
                grvSuccessful.DataSource = col;
                grvSuccessful.DataBind();

            } // grvSuccessful_PageIndexChanging

            protected void grvFailed_PageIndexChanging(object sender, GridViewPageEventArgs e)
            {
                grvFailed.PageIndex = e.NewPageIndex;
                StringASLTelecomCollection col = new StringASLTelecomCollection();
                col = (StringASLTelecomCollection)Session["ASLInvalidsCollection"];
                grvFailed.DataSource = col;
                grvFailed.DataBind();
            }

            protected void grvFailed_Sorting(object sender, GridViewSortEventArgs e)
            {
                if (this.hidOrderByFailed.Value == e.SortExpression)
                {
                    if (this.hidOrderDirFailed.Value == "0")
                        this.hidOrderDirFailed.Value = "1";
                    else
                        this.hidOrderDirFailed.Value = "0";
                } // if
                else
                    this.hidOrderDirFailed.Value = "1";

                int pagina = ((grvFailed.PageCount == 0) ? grvFailed.PageIndex : grvFailed.PageIndex + 1);
                this.hidOrderByFailed.Value = e.SortExpression;

                CargarDatosInvalids(pagina, e.SortExpression, int.Parse(this.hidOrderDirFailed.Value));
            }

            protected void grvSuccessful_Sorting(object sender, GridViewSortEventArgs e)
            {
                if (this.hidOrderBySuccessful.Value == e.SortExpression)
                {
                    if (this.hidOrderDirSuccessful.Value == "0")
                        this.hidOrderDirSuccessful.Value = "1";
                    else
                        this.hidOrderDirSuccessful.Value = "0";
                } // if
                else
                    this.hidOrderDirSuccessful.Value = "1";

                int pagina = ((grvSuccessful.PageCount == 0) ? grvSuccessful.PageIndex : grvSuccessful.PageIndex + 1);
                this.hidOrderBySuccessful.Value = e.SortExpression;

                CargarDatosValids(pagina, e.SortExpression, int.Parse(this.hidOrderDirSuccessful.Value));
            } // grvFailed_PageIndexChanging

        #endregion


    } // class
} // namespace
